package com.zdkj.subway.check.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zdkj.admin.api.entity.SysUser;
import com.zdkj.common.core.constant.SecurityConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.subway.check.entity.*;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.mapper.*;
import com.zdkj.subway.check.result.Result;
import com.zdkj.subway.check.service.CommonService;
import com.zdkj.subway.check.util.CheckAccount;
import com.zdkj.subway.check.util.DateFormat;
import com.zdkj.subway.check.util.JdbcUtil;
import com.zdkj.subway.check.util.UserInfo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/check")
@Slf4j
public class CommonController {

    @Resource
    private SwPmDeviceOperationCodeMapper swPmDeviceOperationCodeMapper;
    @Resource
    private SwPmInternetTicketEquipmentCodeMapper swPmInternetTicketEquipmentCodeMapper;
    @Resource
    private SwParamLineMapper swPmLineMapper;
    @Resource
    private SwParamStationMapper swParmStationMapper;
    @Resource
    private SwPmTvmCodeMapper swPmTvmCodeMapper;
    @Resource
    private SysDictMapper sysDictMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Resource
    SysDeptMapper sysDeptMapper;
    @Resource
    SwPmReportPathMapper swPmReportPathMapper;
    @Resource
    RedisTemplate redisTemplate;
    @Autowired
    private CommonService commonService;



    /**
     * 获取设备操作号
     * @param swPmDeviceOperationCode
     * @return
     */
    @RequestMapping("/getSwPmDeviceOperationCodeList")
    @ApiOperation(value = "获取设备操作号", notes = "获取设备操作号")
    public Result getSwPmDeviceOperationCodeList(SwPmDeviceOperationCode swPmDeviceOperationCode){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            //获取设备操作号
            List<SwPmDeviceOperationCode> all = swPmDeviceOperationCodeMapper.getSwPmDeviceOperationCodeList(swPmDeviceOperationCode);
            res.setData(all);
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
            res.setMsg("查询设备列表出错");
        }
        return res;
    }

    /**
     * 获取互联网售票机编号
     * @param swPmInternetTicketEquipmentCode
     * @return
     */
    @RequestMapping("/getSwPmInternetTicketEquipmentCodeList")
    @ApiOperation(value = "获取互联网售票机编号", notes = "获取互联网售票机编号")
    public Result getSwPmInternetTicketEquipmentCodeList(SwPmInternetTicketEquipmentCode swPmInternetTicketEquipmentCode){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            //获取互联网售票机编号
            List<SwPmInternetTicketEquipmentCode> all = swPmInternetTicketEquipmentCodeMapper.getSwPmInternetTicketEquipmentCodeList(swPmInternetTicketEquipmentCode);
            res.setData(all);
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
            res.setMsg("查询设备列表出错");
        }
        return res;
    }


    /**
     * 获取互联网设备编号
     * @return
     */
    @RequestMapping("/getEquipmentCode")
    @ApiOperation(value = "获取互联网设备编号", notes = "获取互联网设备编号")
    public List<Map<String, Object>> getEquipmentCode(String lineCode,String stationCode){
        try {
            //获取互联网设备编号
            String sql ="select * from sw_pm_internet_ticket_equipment_code where 1=1 ";
            if(org.apache.commons.lang3.StringUtils.isNotEmpty(lineCode)){
                sql+=" and line_code ='"+lineCode+"' ";
            }
            if(org.apache.commons.lang3.StringUtils.isNotEmpty(stationCode)){
                sql+=" and station_code ='"+stationCode+"' ";
            }
            List<Map<String, Object>> maps = JdbcUtil.exeSqlQuery(sql);
            return maps;
        }catch (Exception e){
            log.error("{}",e);
            return new ArrayList<>();
        }
    }

    /**
     * 获取线路
     * @param swParamLine
     * @return
     */
    @RequestMapping("/getLineAll")
    @ApiOperation(value = "获取线路", notes = "获取线路")
    public List<SwParamLine> getLineAll(SwParamLine swParamLine){
        try {
         
			/*Map<String,Object> param=new HashMap<>();
            param.put("serviceid","1");
            //获取线路
            List<SwParamLine> reportErrorAlterAppays= swPmLineMapper.selectByMap(param);*/
			List<SwParamLine> reportErrorAlterAppays= swPmLineMapper.getLineAll();

            return reportErrorAlterAppays;
			
        }catch (Exception e){
            log.error("{}",e);
            swParamLine.setName(swParamLine.getCode());
            return new ArrayList<>();
        }
    }
    /**
     * 获取车站
     * @param swParamStation
     * @return
     */
    @RequestMapping("/getStationAll")
    @ApiOperation(value = "获取车站", notes = "获取车站")
    public List<SwParamStation> getSwPmDeviceOperationCodeList(SwParamStation swParamStation){
        try {
            Map<String,Object> param=new HashMap<>();
            //获取车站
            List<SwParamStation> reportErrorAlterAppays= swParmStationMapper.selectByMap(param);
            return reportErrorAlterAppays;
        }catch (Exception e){
            log.error("{}",e);
            swParamStation.setName(swParamStation.getCode());
            return new ArrayList<>();
        }
    }

    /**
     * 获取TVM编号
     * @param swPmTvmCode
     * @return
     */
    @RequestMapping("/getSwPmTvmCodeList")
    @ApiOperation(value = "获取TVM编号", notes = "获取TVM编号")
    public List<SwPmTvmCode> getSwPmTvmCodeList(SwPmTvmCode swPmTvmCode){
        try {
            //获取TVM编号
            List<SwPmTvmCode> reportErrorAlterAppays= swPmTvmCodeMapper.getSwPmTvmCodeList(swPmTvmCode);
            return reportErrorAlterAppays;
        }catch (Exception e){
            log.error("{}",e);
            return new ArrayList<>();
        }
    }

    /**
     * 根据主数据code编码获取主数据列表
     */
    @RequestMapping("/getSysDictItemList")
    @ApiOperation(value = "根据主数据code编码获取主数据列表", notes = "根据主数据code编码获取主数据列表")
    public Result getSysDictItemList(Page page, @RequestParam Map<String,String> param){
        Result result=new Result(ResultDetailMsg.OK);
        try {
            //根据主数据code编码获取主数据列表
            List<Map<String,Object>> sysDictItems= sysDictMapper.getSysDictItemList(param);
            result.setData(sysDictItems);
        }catch (Exception e){
            log.error("{}",e);
            result.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
            result.appendMsg("查询主数据失败");
        }
        return result;
    }


    /**
     * 查询所有字典
     */
    @RequestMapping("/getSysDictMapping")
    @ApiOperation(value = "查询所有字典", notes = "查询所有字典")
    public Result getSysDictMapping(Page page, @RequestParam Map<String,String> param){
        Result result=new Result(ResultDetailMsg.OK);
        try {
            long l = System.currentTimeMillis();
            //查询所有字典
            List<Map<String,Object>> sysDictItems= sysDictMapper.getSysDictMapping(param);
            long l2 = System.currentTimeMillis();
            System.out.println(l2-l);
            Map<Object,Object> res=new HashMap<>();
            for(Map<String,Object> map:sysDictItems){
                String values = String.valueOf(map.get("value"));
                JSONArray jsonArray=new JSONArray();
                for(String one:values.split(";;")){
                    JSONObject j=new JSONObject();
                    String label=one.split(":：")[0];
                    String value=one.split(":：")[1];
                    j.put("label",label);
                    j.put("value",value);
                    jsonArray.add(j);
                }
                res.put(map.get("type"),jsonArray);
            }
            long l3 = System.currentTimeMillis();
            System.out.println(l3-l2);
            result.setData(res);
        }catch (Exception e){
            log.error("{}",e);
            result.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
            result.appendMsg("查询主数据失败");
        }
        return result;
    }

    /**
     * 查询员工
     */
    @RequestMapping("/getSysUserToLS")
    @ApiOperation(value = "查询员工", notes = "查询员工")
    public Page getSysUserToLS(Page page, @RequestParam Map<String,Object> param){
        //查询员工
        List<SysUser> sysUsers = sysUserMapper.getUsersByRolesOrOther(param);
        page.setData(sysUsers);
        return page;
    }

    /**
     * 根据不同类型发代办
     * @param param
     * @throws Exception
     */
    @RequestMapping("/innerBatch")
    @ApiOperation(value = "根据不同类型发代办", notes = "根据不同类型发代办")
    public void innerBatch(@RequestParam Map<String,Object> param) throws Exception{
        String type = String.valueOf(param.get("type"));
        String configuration = CommonEntity.CONFIGURATION.get(type);
        if(null != param.get("messageLSList")){
            List<SwMessage> swMessages = new ArrayList<>();
            List<Map<String,String>> messageLSList = JSONObject.parseObject(String.valueOf(param.get("messageLSList")), List.class);
            for(Map<String,String> m : messageLSList){
                List<String> list = CommonEntity.URL.get(type);
                //票务管理室部门
                if("JDZYDLCK_004".equals(type)){
                    String payType = String.valueOf(m.get("payType"));
                    if("1".equals(payType)){
                        list = CommonEntity.URL.get(type+"_XJ");
                    }else{
                        list = CommonEntity.URL.get(type="_DZ");
                    }
                }
                if("JDZYDLCK_001".equals(type)){
                    String replyReason = String.valueOf(m.get("replyReason"));
                    if("1".equals(replyReason)){//系统
                        configuration = CommonEntity.CONFIGURATION.get(type+"_R1");
                        list = CommonEntity.URL.get(type+"_R1");
                    }else if("2".equals(replyReason)){
                        configuration = CommonEntity.CONFIGURATION.get(type+"_R2");
                        list = CommonEntity.URL.get(type+"_R2");
                    }
                }
                int flag = 0;
                for(String url : list){
                    if("1000".equals(configuration) && 0!=flag){
                        m.put("lineCode","");
                        m.put("stationCode","");
                        if(1==flag){
                            //客运一部部门ID
                            m.put("deptId",String.valueOf(CommonEntity.DEPT_ID_KY1));
                        }else if(2==flag){
                            //客运二部部门ID
                            m.put("deptId",String.valueOf(CommonEntity.DEPT_ID_KY2));
                        }
                    }
                    if("2000".equals(configuration)){
                        m.put("lineCode","");
                        m.put("stationCode","");
                        //机电一部部门ID
                        m.put("deptId",String.valueOf(CommonEntity.DEPT_ID_JD1));
                        if(1==flag){
                            //机电二部部门ID
                            m.put("deptId",String.valueOf(CommonEntity.DEPT_ID_JD2));
                        }
                    }
                    if("3000".equals(configuration)){
                        m.put("lineCode","");
                        m.put("stationCode","");
                        //系统清分部部门ID
                        m.put("deptId",String.valueOf(CommonEntity.DEPT_ID_QF1));
                    }
                    if("5000".equals(configuration)){
                        m.put("lineCode","");
                        m.put("stationCode","");
                        //票务管理室部门ID
                        m.put("deptId",String.valueOf(CommonEntity.DEPT_ID_PW1));
                    }
                    if("15000".equals(configuration)){
                        String lineCode = String.valueOf(m.get("lineCode"));
                        String stationCode = String.valueOf(m.get("stationCode"));
                        //给客运
                        m.put("lineCode",lineCode);
                        m.put("stationCode",stationCode);
                        m.put("roleCode" , "3");
                    }
                    if("6000".equals(configuration)){
						String lineCode = String.valueOf(m.get("lineCode"));
                        m.put("lineCode","");
                        m.put("stationCode","");			

                        Long deptId =CommonEntity.DEPT_ID_MAP.get(lineCode);//CommonEntity.DEPT_ID_LIST.get(flag);
						//flag++;
                        m.put("deptId",String.valueOf(deptId));
//                        this.setMessage(swMessages,param,url,m);
                        //continue;
                    }
                    if("7000".equals(configuration)){
                        String lineCode = String.valueOf(m.get("lineCode"));
                        String stationCode = String.valueOf(m.get("stationCode"));
                        //给客运
                        m.put("lineCode",lineCode);
                        m.put("stationCode",stationCode);
//                        this.setMessage(swMessages,param,url,m);
                    }
                    flag++;
                    this.setMessage(swMessages,param,url,m);
                }
            }
            R r = commonService.innerBatch(swMessages, SecurityConstants.FROM_IN);
            if(1==r.getCode()){
                throw new Exception();
            }
        }
    }

    /**
     * 添加到站内消息
     * @param swMessages
     * @param param
     * @param url
     * @param m
     */
    private void setMessage(List<SwMessage> swMessages,Map<String,Object> param,String url,Map<String,String> m){
        SwMessage swMessage = new SwMessage();
        swMessage.setTitle(String.valueOf(param.get("title")));
        swMessage.setMsgType(String.valueOf(param.get("msgType")));
        swMessage.setContent(m.get("content"));
        swMessage.setStatus(0);
        swMessage.setUrl(url);
        if (null != param.get("roleCode") && !"".equals(String.valueOf(param.get("roleCode")))) {
            swMessage.setRoleCode(String.valueOf(param.get("roleCode")));
        }
        if(!StringUtils.isEmpty(m.get("sendDeptCode"))){
            swMessage.setSendDeptCode(m.get("sendDeptCode"));
        }
        swMessage.setCreatorId(UserInfo.getId());
        swMessage.setCreatorName(UserInfo.getName());//这个是昵称，原来获取的是账号名
        swMessage.setCreateTime(LocalDateTime.now());
        if(!StringUtils.isEmpty(m.get("lineCode"))){
            swMessage.setLineCode(m.get("lineCode"));
        }
        if(!StringUtils.isEmpty(m.get("stationCode"))){
            swMessage.setStationCode(m.get("stationCode"));
        }
        if(null != m.get("deptId")){
            swMessage.setDeptId(Integer.valueOf(m.get("deptId")));
        }/*else{
            swMessage.setDeptId(SecurityUtils.getUser().getDeptId());
        }*/
        if(!StringUtils.isEmpty(m.get("applyTime"))){
            swMessage.setApplyTime(DateFormat.StringTurnLocalDateTime(m.get("applyTime")));
            swMessage.setApplyTimeDTO(m.get("applyTime"));
        }
        swMessage.setDelFlag("0");
        Date date = new Date();
        SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd");
        String createTimeDTO = dff.format(date);
        swMessage.setCreateTimeDTO(createTimeDTO);
        swMessages.add(swMessage);
    }

    /**
     * 获取车站
     * @param param
     * @return
     */
    @RequestMapping("/getStationByCode")
    @ApiOperation(value = "获取车站", notes = "获取车站")
    public List<SwParamStation> getStationByCode(@RequestParam Map<String,Object> param){
        try {
            //获取车站
            List<SwParamStation> reportErrorAlterAppays= swParmStationMapper.selectByMap(param);
            return reportErrorAlterAppays;
        }catch (Exception e){
            log.error("{}",e);
            return new ArrayList<>();
        }
    }

    /**
     * 根据线路和站点获取车站
     * @param param
     * @return
     */
    @RequestMapping("/getLineAndStationByCode")
    @ApiOperation(value = "根据线路和站点获取车站", notes = "根据线路和站点获取车站")
    public List<SwParamStation> getLineAndStationByCode(@RequestParam Map<String,Object> param){
        try {
            param.put("line_code",param.get("lineCode"));
            param.remove("lineCode");
            //根据线路和站点获取车站
            List<SwParamStation> reportErrorAlterAppays= swParmStationMapper.selectByMap(param);
            return reportErrorAlterAppays;
        }catch (Exception e){
            log.error("{}",e);
            return new ArrayList<>();
        }
    }

    /**
     * 获取部门信息
     * @param sysDept
     * @return
     */
    @RequestMapping("/getSysDept")
    @ApiOperation(value = "获取部门信息", notes = "获取部门信息")
    public Page getSysDept(Page page,SysDept sysDept){
        try {
            //获取部门信息
            List<SysDept> sysDepts= sysDeptMapper.select(sysDept);
            page.setData(sysDepts);
            return page;
        }catch (Exception e){
            log.error("{}",e);
            return new Page();
        }

    }

    /**
     * 获取报表信息
     * @param swPmReportPath
     * @return
     */
    @RequestMapping("/getSwPmReportPath")
    @ApiOperation(value = "获取报表信息", notes = "获取报表信息")
    public Page getSwPmReportPath(Page page,SwPmReportPath swPmReportPath){
        try {
            //获取报表信息
            QueryWrapper<SwPmReportPath> queryWrapper=new QueryWrapper();
            queryWrapper.setEntity(swPmReportPath);
            queryWrapper.eq("STATUS","1");
            List<SwPmReportPath> sysDepts= swPmReportPathMapper.selectList(queryWrapper);
            page.setData(sysDepts);
            return page;
        }catch (Exception e){
            log.error("{}",e);
            return new Page();
        }

    }

    /**
     *
     * @param account 账户
     * @param password 密码
     * @param isCheckRole 是否校验角色
     * @param roleCode 角色代码
     * @return
     */
    @RequestMapping("/checkAccountPassword")
    @ApiOperation(value = "是否校验角色", notes = "是否校验角色")
    public Result checkAccountPassword(String account,String password,Boolean isCheckRole,String roleCode){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            List<Map<String,Object>> checkAccountRole=new ArrayList<>();
            if(isCheckRole){
                checkAccountRole= sysUserMapper.checkAccountRole(account,roleCode);
                if(checkAccountRole==null || checkAccountRole.size()==0){
                    res.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
                    res.setMsg("角色校验未通过！");
                    return res;
                }
            }
            Map<String,Object> pa=new HashMap<>();
            pa.put("username",account);
            List<SysUser> sysUsers = sysUserMapper.selectByMap(pa);
            String userCode="";
            if(sysUsers!=null && sysUsers.size()>0){
                userCode = sysUsers.get(0).getUserCode();
            }

            R r = CheckAccount.checkAccount(userCode, password);
            JSONObject s =JSONObject.parseObject( JSONObject.toJSONString(sysUsers.get(0)));
            if(r.getCode()!=0){
                res.setCode(r.getCode());
                res.setMsg(r.getMsg());
                return res;
            }
            SetOperations<String, String> stringStringSetOperations = redisTemplate.opsForSet();
            UUID uuid=UUID.randomUUID();
            stringStringSetOperations.add(UserInfo.getUserCode()+account,uuid.toString());
            redisTemplate.expire(UserInfo.getUserCode()+account,60, TimeUnit.SECONDS);
            s.put("token",uuid.toString());
            s.put("check",r.getData());
            res.setData(s);
            res.setMsg("校验通过，请在60秒内确认提交数据，否则将认证失效！");
            return res;
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
            res.setMsg("校验失败！");
            return res;
        }
    }

    /**
     * 查询车站原始数据录入修改报表参数表
     * @return
     */
    @RequestMapping("/getReplayPeriod")
    @ApiOperation(value = "查询车站原始数据录入修改报表参数表", notes = "查询车站原始数据录入修改报表参数表")
    public Result getReplayPeriod(){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            //查询车站原始数据录入修改报表参数表
            List<Map<String, Object>> maps = JdbcUtil.exeSqlQuery("select * from sw_pm_report_alter");
            Map<String, Object> map = maps.get(0);
            res.setData(map);
            return res;
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
            res.setMsg("校验失败！");
            Map<String, Object> map =new HashMap<>();
            map.put("alter_limit",0);
            res.setData(map);
            return res;
        }
    }

    /**
     * 获取票种
     * @return
     */
    @RequestMapping("/getpm_ticket_card_type_param")
    @ApiOperation(value = "获取票种", notes = "获取票种")
    public List<Map<String, Object>> getpm_ticket_card_type_param(){
        try {
            //获取票种
            List<Map<String, Object>> maps = JdbcUtil.exeSqlQuery("select * from sw_pm_ticket_card_type_param where del_flag =0" +
                    " and MAIN_EN_NAME='YXCP'");
            return maps;
        }catch (Exception e){
            log.error("{}",e);
            return new ArrayList<>();
        }
    }

    /**
     * 获取用户数据通过编号
     * @return
     */
    @RequestMapping("/getUserDataByJobNo")
    @ApiOperation(value = "获取钱箱编号", notes = "获取钱箱编号")
    public List<SysUser> getUserDataByJobNo(String userCodes){
        try {
            userCodes=userCodes.replaceAll("\\s+","");
            QueryWrapper<SysUser> queryWrapper=new QueryWrapper<SysUser>();
            queryWrapper.in("user_code",userCodes.split(","));
            List<SysUser> sysUsers = sysUserMapper.selectList(queryWrapper);
            return sysUsers;
        }catch (Exception e){
            log.error("{}",e);
            return new ArrayList<>();
        }
    }

    /**
     * 获取钱箱编号
     * @return
     */
    @RequestMapping("/getTvmCashBoxCode")
    @ApiOperation(value = "获取钱箱编号", notes = "获取钱箱编号")
    public List<Map<String, Object>> getTvmCashBoxCode(String lineCode,String stationCode){
        try {
            //获取钱箱编号
            String sql ="select id,line_code,station_code,cashbox_code,status,dept_id,creator_id,creator_name,create_time,del_flag from sw_pm_tvm_cashbox_code where 1=1 ";
            if(org.apache.commons.lang3.StringUtils.isNotEmpty(lineCode)){
                sql+=" and line_code ='"+lineCode+"' ";
            }
            if(org.apache.commons.lang3.StringUtils.isNotEmpty(stationCode)){
                sql+=" and station_code ='"+stationCode+"' ";
            }
            List<Map<String, Object>> maps = JdbcUtil.exeSqlQuery(sql);
            return maps;
        }catch (Exception e){
            log.error("{}",e);
            return new ArrayList<>();
        }
    }


}
